package com.fivestyle.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fivestyle.common.lang.Const;
import com.fivestyle.common.lang.Result;
import com.fivestyle.common.result.R;
import com.fivestyle.entity.User;
import com.fivestyle.entity.vo.RegisterVo;
import com.fivestyle.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 张代钊
 * @since 2021-08-04
 */
@RestController
@RequestMapping("/onlinebook/user")
public class UserController extends BaseController{

    @Autowired
    private UserService userService;

//    根据token获取用户信息
    @GetMapping("getMemberInfo")
    public R getMemberInfo(HttpServletRequest request) {

        return userService.getMemberInfo(request);
    }

//    更新用户信息
    @Transactional
    @PutMapping("updateUserInfo")
    public R updateUserInfo(@RequestBody User user){
        try {
            boolean b = userService.updateById(user);
            return R.ok().data("userInfo",user);
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error().message("用户信息更新失败！");
        }
    }

//    登录
    @ApiOperation(value = "用户登录",notes = "传入用户实体类进行登录")
    @PostMapping("login")
    public R loginUser(@RequestBody User member) {
        return userService.login(member);
    }

//    注册
    @ApiOperation(value = "注册用户",notes = "在用户实体类基础上，多加一个code验证码字段进行注册")
    @PostMapping("register")
    public R registerUser(@RequestBody RegisterVo registerVo) {
        return userService.register(registerVo);
    }

//    邮箱发送验证码
    @ApiOperation(value = "发送验证码",notes = "通过邮箱发送验证码")
    @GetMapping("sendMail/{email}")
    public R sendMail(@PathVariable String email){

        return userService.sendMail(email);
    }


    /**
     * 后台控制层
     */

    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('web:user:list')")
    public Result info(@PathVariable("id") String id) {
        User User = userService.getById(id);
        Assert.notNull(User, "找不到该用户");
        return Result.succ(User);
    }

    @GetMapping("/list")
    @PreAuthorize("hasAuthority('web:user:list')")
    public Result list(String nickname) {

        Page<User> pageData=userService.page(getPage(),new QueryWrapper<User>()
                .like(StrUtil.isNotBlank(nickname), "nickName", nickname));
        return Result.succ(pageData);
    }

//    新增用户
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('web:user:save')")
    public Result save(@Validated @RequestBody User User) {

        // 默认密码
        String password = passwordEncoder.encode(Const.DEFULT_PASSWORD);
        User.setPassword(password);
        // 默认头像
        User.setAvator(Const.DEFULT_AVATAR);
        userService.save(User);
        return Result.succ(User);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('web:user:update')")
    public Result update(@Validated @RequestBody User User) {
        userService.updateById(User);
        return Result.succ(User);
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('web:user:delete')")
    public Result delete(@RequestBody String[] ids) {
        userService.removeByIds(Arrays.asList(ids));
        return Result.succ("");
    }

//    重置密码
    @PostMapping("/repass")
    @PreAuthorize("hasAuthority('web:user:repass')")
    public Result repass(@RequestBody String userId) {
        User User = userService.getById(userId);
        // 默认密码
        String password = passwordEncoder.encode(Const.DEFULT_PASSWORD);
        User.setPassword(password);

        userService.updateById(User);
        return Result.succ("");
    }

}

